package com.ex02.ylw;

import com.util.BufferSize;
import com.util.Resource;
import com.util.WrapperUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.*;
import java.util.Locale;

/**
 * 直接只提供输出对象PrintWrite
 * Created by yangliwei on 2017/7/21.
 */
public class Response implements ServletResponse {
    private Request request;

    //为了方便输出字符串
    private PrintWriter printWriter;

    private OutputStream output;

    /**
     * 设置socket传进来的OutputStream
     *
     * @param output
     */
    public Response(OutputStream output) {
        this.output = output;
    }

    /**
     * 设置request
     *
     * @param request
     */
    public void setRequest(Request request) {
        this.request = request;
    }

    //发送静态资源,主要供StaticResourceProcee类使用
    public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BufferSize.RESPONSE_BUFFER_SIZE.getSize()];
        FileInputStream fis = null;
        File file = new File(Resource.STATIC_SOURCE.getProperty()+request.getUri());
        try {
            fis = new FileInputStream(file);
            int temp;
            //这个要写在finally前面，要不然输出都关闭了还特么搞个鸡巴
            while ((temp = fis.read(bytes, 0, BufferSize.RESPONSE_BUFFER_SIZE.getSize())) != -1) {
                output.write(bytes, 0, temp);
            }
        } catch (FileNotFoundException e) {
            String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                    "Content-Type: text/html\r\n" +
                    "Content-Length: 23\r\n" +
                    "\r\n" +
                    "<h1>File Not Found</h1>";
            output.write(errorMessage.getBytes());
        } finally {
            if (fis != null)
                fis.close();
        }


    }

    public static void main(String[] args) throws IOException {
        WrapperUtil.createWrapper(Response.class,ServletResponse.class);
    }

    @Override
    public String getCharacterEncoding() {
        return null;
    }

    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        return null;
    }

    //为了直接输出字符
    @Override
    public PrintWriter getWriter() throws IOException {
        this.printWriter = new PrintWriter(output, true);
        return this.printWriter;
    }

    @Override
    public void setContentLength(int i) {

    }

    @Override
    public void setContentType(String s) {

    }

    @Override
    public void setBufferSize(int i) {

    }

    @Override
    public int getBufferSize() {
        return 0;
    }

    @Override
    public void flushBuffer() throws IOException {

    }

    @Override
    public void resetBuffer() {

    }

    @Override
    public boolean isCommitted() {
        return false;
    }

    @Override
    public void reset() {

    }

    @Override
    public void setLocale(Locale locale) {

    }

    @Override
    public Locale getLocale() {
        return null;
    }
}
